package com.wry.juc;

import java.util.LinkedList;
import java.util.Queue;

/**
 * <h1>  </h1>
 *
 * @author wry
 * @since 2025.03.30
 */
public class ProducerConsumerExample {

    // 队列最大容量
    private static final int CAPACITY = 10;
    private final Queue<Integer> queue = new LinkedList<>();


    public static void main(String[] args) {
        ProducerConsumerExample producerConsumerExample = new ProducerConsumerExample();
        Producer producer = producerConsumerExample.new Producer();
        Consumer consumer = producerConsumerExample.new Consumer();
        consumer.start();
        producer.start();

    }


    class Producer extends Thread {
        @Override
        public void run() {
            int value = 0;
            while (true) {
                synchronized (queue) {
                    while (queue.size() == CAPACITY) { // 队列满了 进入等待
                        try {
                            System.out.println("【生产者】 队列满啦阻塞中");
                            queue.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                    value++;
                    System.out.println("【生产者】生产了一个..."+value);
                    queue.offer(value);
                    System.out.println("【生产者】队列容量=" + queue.size());
                    // 唤醒消费者
                    queue.notify();
                }
                try {
                    sleep(1000L);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    class Consumer extends Thread {
        @Override
        public void run() {
            while (true) {
                synchronized (queue) {
                    while (queue.size() == 0) { // 队列空了 进入等待
                        try {
                            System.out.println("【消费者】 队列空啦 阻塞中");
                            queue.wait();

                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                    Integer poll = queue.poll();
                    System.out.println("【消费者】消费了一个..." + poll);
                    System.out.println("【消费者】 队列容量=" + queue.size());
                    // 唤醒消费者
                    queue.notify();
                }
                try {
                    sleep(1000L);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
}
